/*
 * TcpUdp_F.cpp
 *
 *  Created on: 2014年9月9日
 *      Author: finder
 */

#include "tcp_udp_f.h"

#include <sys/socket.h>


#include<fcntl.h>

tcpf_t::tcpf_t(FD_t fd)
:m_fd(fd)
{
	FD_ZERO(&_fdset);
	FD_SET(fd, &_fdset);
}

tcpf_t::tcpf_t(FD_t fd,const sockaddr_in* sin)
:_sin(*sin),
m_fd(fd)
{
	FD_ZERO(&_fdset);
	FD_SET(fd, &_fdset);
}

const sockaddr_in& tcpf_t::get_addr()
{
	return _sin;
}

BOOL tcpf_t::is_valid()
{
	return m_fd > 0;
}

BOOL tcpf_t::is_connected()
{
	U8 uTmp;
	return is_valid()
			&& (read(&uTmp,1,MSG_PEEK) != 0);
}

void tcpf_t::set_block(BOOL bBlock)
{
	int flag = fcntl(m_fd,F_GETFL,0);

	if (bBlock) {
		flag &= ~O_NONBLOCK;
		flag |= O_SYNC;
	}
	else {
		flag &= O_SYNC;
		flag |= O_NONBLOCK;
	}

	fcntl(m_fd,F_SETFL,flag);
}

ssize_t tcpf_t::read(void* outBuf,ssize_t iLen,int iFlags)
{
	return recv(m_fd,outBuf,iLen,iFlags);
}

ssize_t tcpf_t::write(const void* inBuf,ssize_t iLen,int iFlags)
{
	return send(m_fd,inBuf,iLen,iFlags);
}

BOOL tcpf_t::wait_for_receive(U32 uMilliSeconds)
{
	struct timeval tmWait;
	tmWait.tv_sec = uMilliSeconds / 1000;
	tmWait.tv_usec = (uMilliSeconds % 1000) * 1000;

	fd_set fdsCheck = _fdset;
	int iRes = select(m_fd+1,&fdsCheck,NULL,NULL,&tmWait);
	switch (iRes)
	{
	case 0:
	case -1:
		return RETURN_ERROR_F;
		break;
	default:
		break;
	}
	return FD_ISSET(m_fd,&fdsCheck) ? RETURN_SUCCESS_F : RETURN_ERROR_F;
}




















udpf_t::udpf_t(FD_t fd)
{
	_fd = fd;
}

BOOL udpf_t::is_valid()
{
	return _fd > 0;
}

ssize_t udpf_t::read(void* outBuf,ssize_t iLen,int iFlags)
{
	return recvfrom(_fd,outBuf,iLen,iFlags,NULL,NULL);
}

ssize_t udpf_t::write(const void* inBuf,ssize_t iLen,int iFlags)
{
	return sendto(_fd,inBuf,iLen,iFlags,NULL,0);
}




